package com.gdpu.project.util.xml;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Line2DXML {
	public Boolean createXml(Map<String, String> map, String fileName) {
		Boolean flag = false;
		try {
			/** 定义创建时间 */
			SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			String date = s.format(new Date());

			/** 建立document对象 */
			Document document = DocumentHelper.createDocument();

			/** 建立XML文档的根graph */
			Element graphElement = document.addElement("graph");

			/** 加入一行注释 */
			graphElement.addComment("This is a new XML file,创建日期：" + date);

			/** 创建根节点属性 */
			graphElement.addAttribute("caption", "广东药学院招生情况表");
			graphElement.addAttribute("subcaption", "10年");
			graphElement.addAttribute("xAxisName", "年份");
			graphElement.addAttribute("decimalPrecision", "0");
			graphElement.addAttribute("yAxisMinValue", "0");
			graphElement.addAttribute("yAxisName", "amount");
			graphElement.addAttribute("showNames", "1");
			graphElement.addAttribute("showValues", "1");
			graphElement.addAttribute("showAlternateHGridColor", "1");
			graphElement.addAttribute("AlternateHGridColor", "ff5904");
			graphElement.addAttribute("divLineColor", "ff5904");
			graphElement.addAttribute("divLineAlpha", "20");
			graphElement.addAttribute("alternateHGridAlpha", "5");

			/** 创建set节点 */
			Set<String> keys = map.keySet();
			Iterator<String> it = keys.iterator();
			while (it.hasNext()) {
				String name = it.next();
				String value = map.get(name);
				Element setElement = graphElement.addElement("set");
				setElement.addAttribute("name", name);
				setElement.addAttribute("value", value);
				setElement.addAttribute("hoverText", name + "年");
			}

			/** 将document中的内容写入文件中 */
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			XMLWriter writer = new XMLWriter(new OutputStreamWriter(
					new FileOutputStream(fileName),

					"UTF-8"));
			writer.write(document);
			writer.close();
			flag = true;

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("创建XML文件失败！");
		}
		return flag;
	}
}